#define _CRT_SECURE_NO_WARNINGS 1
#include <iostream>

using namespace std;

 struct ListNode 
 {
    int val;
    ListNode *next;
    ListNode() : val(0), next(nullptr) {}
    ListNode(int x) : val(x), next(nullptr) {}
    ListNode(int x, ListNode *next) : val(x), next(next) {}
 };
 
class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        if (head == nullptr || head->next == nullptr) return head;

        ListNode* newhead = new ListNode(0);
        newhead->next = head;
        ListNode* prev = newhead;
        ListNode* cur = head;
        ListNode* nextnode = cur->next;
        ListNode *nnext = nextnode->next;

        while (cur && nextnode)
        {
            prev->next = nextnode;
            nextnode->next = cur;
            cur->next = nnext;

            prev = prev->next->next;
            cur = prev->next;
            if (cur) {
                nextnode = cur->next;
                if (nextnode)
                    nnext = nextnode->next;
            }
        }
        return newhead->next;
    }
};

int main()
{
    Solution s;
    ListNode* node1 = new ListNode(1);
    ListNode* node2 = new ListNode(2);
    ListNode* node3 = new ListNode(3);
    ListNode* node4 = new ListNode(4);
    
    node1->next = node2;
    node2->next = node3;
    node3->next = node4;

    s.swapPairs(node1);
    return 0;
}